//
//  Home_goodList_Controller.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/2/19.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "Home_goodList_Controller.h"
//untils
#import "UIColor+Hex.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
#import "UIImage+ColorToImage.h"
#import "Global.h"
#import "FMDBManager.h"
//view
#import "Strore_TeHui_Cell.h"
#import "Strort_Breakfast_Bottom.h"
#import "EmptyPageView.h"
//controllers
#import "Strore_detailController.h"
#import "AppDelegate.h"
#import "RDVTabBarController.h"
//vendor
#import "MJRefresh.h"
#import "MTA.h"
@interface Home_goodList_Controller ()<UITableViewDelegate,UITableViewDataSource,Strort_Breakfast_BottomDelegate>
{
    NSInteger _requestPage;//当前请求页
    NSInteger _totalCount;//数据总条数
    CALayer     *layer;
    CGRect rectx;
}
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)UILabel *remindInfoLabel;
@property(nonatomic, strong)EmptyPageView *emptyPageView;
@property (nonatomic,strong) UIBezierPath *path;
@property (nonatomic,strong)UIImage *goodImage;
@property (nonatomic ,strong) Strort_Breakfast_Bottom  *shopingCarView;//购物车视图
@end

@implementation Home_goodList_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    _requestPage = 1;
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    self.title =self.listName;
    _dataSource = [[NSMutableArray alloc]init];
    [self setupSubView];
    [self addBackNavItem];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
    
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self loadsearchResultDataWithPage:_requestPage requestCount:kRequestLimit];
        
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"首页查看更多"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"首页查看更多"];
}
#pragma mark -- request data
- (void)loadsearchResultDataWithPage:(NSInteger)page  requestCount:(NSInteger)count {
    //请求参数说明： SIGNATURE  设备识别码
    //      STOREID     商品ID
    //      SIZE         要获取的关键字数量
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.storeID] forKey:@"STOREID"];
    [parameter setObject:[NSNumber numberWithInteger:page] forKey:@"PAGENUM"];
    [parameter setObject:[NSNumber numberWithInteger:count] forKey:@"PAGESIZE"];
    [parameter setObject:self.listTag forKey:@"TAGCODE"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"goods/listByTag" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态
            if ([state isEqualToString:@"0"]) {//请求成功
                _totalCount = [[NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"TOTALROW"]] integerValue];
                if (_requestPage == 1) {//请求第一页清空数据
                    [weakSelf.dataSource removeAllObjects];
                }
                [weakSelf.dataSource addObjectsFromArray:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"LIST"]];
                [weakSelf.tableView reloadData];
                if (_dataSource.count==0)
                {
                    _emptyPageView.hidden=NO;
                    weakSelf.shopingCarView.hidden = YES;
                }else{
                    _emptyPageView.hidden=YES;
                    weakSelf.shopingCarView.hidden = NO;
                }
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
        }
         [weakSelf endRefresh];
        
    } failure:^(bool isFailure) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        _emptyPageView.hidden=NO;
        weakSelf.shopingCarView.hidden = YES;
        [weakSelf endRefresh];
        
    }];
    
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"TableViewCellIdentifier";
    Strore_TeHui_Cell *cell = (Strore_TeHui_Cell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[Strore_TeHui_Cell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor = [UIColor whiteColor];
    }
    cell.delegate = (id<Strore_TeHui_CellDelegate>)self;
    cell.indexPath = indexPath;
    NSDictionary *dataDic = [self.dataSource objectAtIndex:indexPath.row];
    [cell updatawithData:dataDic withType:1];
    return cell;
    
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return HightScalar(130);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
    Strore_detailController *detailVC = [[Strore_detailController alloc]init];
    NSDictionary *dataDic = [self.dataSource objectAtIndex:indexPath.row];
    detailVC.goodsID = [NSString stringTransformObject:[dataDic objectForKey:@"ID"]];
    detailVC.isSelf = [NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark --  Strore_TeHui_CellDelegate 加入购入车
-(void)addShoppingCarWithIndex:(NSIndexPath *)indexPath{
    //数据源
    NSDictionary *dataDic = [self.dataSource objectAtIndex:indexPath.row];
    [self inToFmdbShoppingCharWithDictionary:dataDic];
    CGRect rectInTableView = [_tableView rectForRowAtIndexPath:indexPath];
    
    CGRect rect = [_tableView convertRect:rectInTableView toView:[_tableView superview]];
    rectx=rect;
    //
    self.path = [UIBezierPath bezierPath];
    [_path moveToPoint:CGPointMake(VIEW_WIDTH-20, rectx.origin.y+50)];
    
    [_path addQuadCurveToPoint:CGPointMake(35,CGRectGetMinY(self.shopingCarView.frame)+10) controlPoint:CGPointMake(150, rectx.origin.y)];
    
    [self startAnimation];
    
}
#pragma mark -- 购物车跳转
-(void)gotoShoppingCar
{
    [self.navigationController popToRootViewControllerAnimated:NO];
    
    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(action) userInfo:nil repeats:NO];
}
-(void)action
{
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate selectedControllerAtTabBarIndex:3];
}
-(void)inToFmdbShoppingCharWithDictionary:(NSDictionary*)dicData
{
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSString *shopID=[NSString stringISNull:mode.storeID];
    NSString *goodID=[NSString stringTransformObject:[dicData objectForKey:@"ID"]];
    NSString *name =[NSString stringTransformObject:[dicData objectForKey:@"NAME"]];
    _goodImage =[UIImage createImageWithImageUrlString:[NSString stringTransformObject:[dicData objectForKey:@"THUMB"]]];
    if (_goodImage==nil) {
        _goodImage=[UIImage imageNamed:@"productDetail_Default"];
    }
    NSData *picture =UIImagePNGRepresentation(_goodImage);
    NSString *type=@"";
    NSString *price=[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dicData objectForKey:@"SELLPRICE"]] floatValue]];
    NSString *oldprice=[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dicData objectForKey:@"MARKETPRICE"]] floatValue]];
    NSString *ischoose =@"1";
    NSString *isProprietary =[NSString stringTransformObject:[dicData objectForKey:@"ISSELF"]];
    if ([isProprietary isEqualToString:@"1"]) {
        shopID =@"";
    }
    NSMutableDictionary *goodSqlite=[[FMDBManager sharedManager]QueryDataWithShopID:shopID goodID:goodID];
    if (goodSqlite.count ==0) { //购物车没数据 先存
        NSString *buynum= @"1";
        [[FMDBManager sharedManager]InsertWithshopID:shopID goodID:goodID name:name Picture:picture type:type price:price oldprice:oldprice buynum:buynum ischoose:ischoose isProprietary:isProprietary];
        
    }else{//购物车有数据 更新数据
        NSString *str=[goodSqlite objectForKey:@"buynum"];
        if ([isProprietary isEqualToString:@"1"])
        {
            [[FMDBManager sharedManager]deleteOneDataWithgoodID:goodID];
        }else{
            [[FMDBManager sharedManager]deleteOneDataWithShopID:shopID goodID:goodID];
        }
        //字符串 变数字 然后加减完 变回字符串
        NSInteger buynum =str.integerValue;
        buynum++;
        NSString *srr=[NSString stringWithFormat:@"%ld",(long)buynum];
        [[FMDBManager sharedManager]InsertWithshopID:shopID goodID:goodID name:name Picture:picture type:type price:price oldprice:oldprice buynum:srr ischoose:ischoose isProprietary:isProprietary];
    }
    
    
}
//改变圆标数量
-(void)setTotalSingularText
{
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableArray *array=[[FMDBManager sharedManager]QueryDataWithshopID:mode.storeID];
    NSInteger totalNum = 0;
    for (NSDictionary *dic in array) {
        NSString *buynum =[dic objectForKey:@"buynum"];
        
        totalNum=totalNum+buynum.integerValue;
    }
    _shopingCarView.totalSingular.text =[NSString stringWithFormat:@"%ld",(long)totalNum];
    if ([_shopingCarView.totalSingular.text isEqualToString:@"0"]) {
        _shopingCarView.totalSingular.hidden =YES;
    }else{
        _shopingCarView.totalSingular.hidden =NO;
    }
}
#pragma mark - 上拉/下拉  更新数据
-(void)headerRereshing {
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        _requestPage = 1;
        [self loadsearchResultDataWithPage:_requestPage requestCount:kRequestLimit];
    }else{
        [self endRefresh];
        
    }
    
}

-(void)footerRereshing
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        if (_requestPage*kRequestLimit < _totalCount) {
            _requestPage++;
            [self loadsearchResultDataWithPage:_requestPage requestCount:kRequestLimit];
        } else {
             [_tableView setFooterRefreshingText:@"已加载完全部商品~"];
            [self endRefresh];
        }
    }else{
        [self endRefresh];
    }
    
}
- (void)endRefresh
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

#pragma makr -- 初始化视图
- (void)setupSubView {
    
    CGRect rect = CGRectMake(0
                             , 0
                             , CGRectGetWidth(self.view.bounds)
                             , CGRectGetHeight(self.view.bounds) - 64);
    _tableView = [[UITableView alloc]initWithFrame:rect style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    UIView *footView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 1)];
    _tableView.tableFooterView=footView;
    // _tableView.tableFooterView = _remindInfoLabel;
    //添加下拉刷新
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //添加上拉加载更多
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.view addSubview:_tableView];

    //无地址显示视图
    _emptyPageView = [[EmptyPageView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 64 - 64) EmptyPageViewType:kHomeGoodListView];
    _emptyPageView.hidden =YES;
    _emptyPageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_emptyPageView];
    
    }

- (Strort_Breakfast_Bottom*)shopingCarView {
    if (!_shopingCarView) {
        Strort_Breakfast_Bottom *shopingCarview =[[Strort_Breakfast_Bottom alloc]initWithFrame:CGRectMake(10
                                                                                                          , VIEW_HEIGHT-70-64
                                                                                                          ,CGRectGetWidth(self.view.bounds)/3+30
                                                                                                          ,50)];
        shopingCarview.totalPrice.hidden = YES;
        shopingCarview.imageView.hidden = YES;
        
        
        [self.view addSubview:shopingCarview];
        _shopingCarView = shopingCarview;
        _shopingCarView.delegate =self;
        [self setTotalSingularText];
        
    }
    return _shopingCarView;
}
#pragma mark--加入物品动画
-(void)startAnimation
{
    if (!layer) {
        
        layer = [CALayer layer];
        layer.contents = (__bridge id)_goodImage.CGImage;
        layer.contentsGravity = kCAGravityResizeAspectFill;
        layer.bounds = CGRectMake(0, 0,30, 30);
        [layer setCornerRadius:CGRectGetHeight([layer bounds]) / 2];
        layer.masksToBounds = YES;
        layer.position =CGPointMake(50, 150);
        [self.view.layer addSublayer:layer];
    }
    [self groupAnimation];
}
-(void)groupAnimation
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    CABasicAnimation *narrowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    narrowAnimation.beginTime = 0.3;
    narrowAnimation.fromValue = [NSNumber numberWithFloat:1.0f];
    narrowAnimation.duration = 0.6f;
    narrowAnimation.toValue = [NSNumber numberWithFloat:0.2f];
    
    narrowAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,narrowAnimation];
    groups.duration = 0.8f;
    groups.removedOnCompletion=NO;
    groups.fillMode=kCAFillModeForwards;
    groups.delegate = self;
    [layer addAnimation:groups forKey:@"group"];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //    [anim def];
    if (anim == [layer animationForKey:@"group"]) {
        
        [layer removeFromSuperlayer];
        layer = nil;
        //购物车按钮动画
        [self setTotalSingularText];
        CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        shakeAnimation.duration = 0.3f;
        shakeAnimation.fromValue = [NSNumber numberWithFloat:-1.5];
        shakeAnimation.toValue = [NSNumber numberWithFloat:1.5];
        shakeAnimation.autoreverses = YES;
        [_shopingCarView.shopCarBtn.layer addAnimation:shakeAnimation forKey:nil];
    }
    //    self.path = [UIBezierPath bezierPath];
    //    [_path moveToPoint:CGPointMake(50, 150)];
    //    [_path addQuadCurveToPoint:CGPointMake(270, 300) controlPoint:CGPointMake(150, 20)];
    
}

-(void)backBtnAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
